import { useState, useRef, useEffect, useCallback } from "react";
import * as _ from "lodash";
import { ChatMessageList } from "./message-list";
import { Button, Upload, Tag, Spin } from "@arco-design/web-react";
import ChatPreview from "./chatPreview";
import { useParams, useLocation } from "react-router-dom";
import { IconToTop, IconSend } from "@arco-design/web-react/icon";
import dayjs from "dayjs";
import { parseMessage } from "@/lib/utils";
import ChatApi from "@/api/chat/chat-api.ts";
import UserApi from "@/api/user/user-api";
import { useDispatch } from "react-redux";
import { setCountBalance } from "@/store/home/homeSlice";
import { userMessageTemplate, aiMessageTemplate } from "./templateMsg";
import PromptTemplate from "./PromptTemplate/index"
import styles from "./index.module.less";
const Chat = () => {
  const userApi = new UserApi();
  const dispatch = useDispatch();
  // 问答loading
  const [chatLoading, setChatLoading] = useState<boolean>(false);
  const data = useParams(); // 获取 URL 中的 id
  const location = useLocation();
  const requestId = useRef<string | any>(data?.chatId);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  // 图片上传
  const [userUploadFileList, setUserUploadFileList] = useState<Array<any>>([]);
  const [uplodaLoading, setUplodaLoading] = useState<boolean>(false);
  // 提问内容
  const [messages, setMessages] = useState<any[]>([]);
  // 当前选中的artifact
  const [currentArtifact, setCurrentArtifact] = useState<any | null>(null);
  const messagesRef = useRef<HTMLDivElement>(null);
  // 提问内容
  const useQuestionRef = useRef<string | undefined | null>(
    location?.state?.userQuestion
  );
  // 上传的图片列表
  const uploadFileList = useRef<Array<any>>(location?.state?.files || []);
  // 事件流
  const eventSource = useRef<EventSource | null>(null);
  // 预览状态
  const [previewStatus, setPreviewStatus] = useState<boolean>(false);
  // 生成结束状态
  const [generateEndStatus, setGenerateEndStatus] = useState<boolean>(false);

  // 提示词
  const [promptState, setPromptState] = useState(false)

  // Ai响应处理
  const handleAIResponse = useCallback((response: string) => {
    try {
      const data = JSON.parse(response);
      // 处理内容
      if (data.finishReason === "STOP") {
        console.log("Stopping event stream.");
        // 停止事件流的逻辑
        setChatLoading(false);
        eventSource.current?.close(); // 停止事件流
        // 生成结束
        setGenerateEndStatus(true);
        getUserBalanceFn();
      } else {
        setPreviewStatus(false);
        // 将AI的内容添加到messages中
        setMessages((prev) => {
          const newMessages = [...prev];
          const lastMessage = newMessages[newMessages.length - 1];
          if (lastMessage && lastMessage.role === "assistant") {
            let aiContent = data?.content;
            lastMessage.content += aiContent;

            // 实时读取流 获取代码
            let parseMessageData = parseMessage(lastMessage.content);
            parseMessageData.forEach((item) => {
              if (item.type === "artifact") {
                // 只有问答时候出现代码内容时可以预览
                setPreviewStatus(true);
                setCurrentArtifact(item.data);
              }
            });
          } else {
            let newAiMessageTemplate = {
              ..._.cloneDeep(aiMessageTemplate),
              id: _.uniqueId("ai_uniqueId_"),
              role: "assistant",
              content: data?.content,
            };
            newMessages.push(newAiMessageTemplate);
          }
          return newMessages;
        });
      }
    } catch (error) {
      console.error("Error parsing AI response:", error);
    }
  }, []);

  // 错误处理
  const handlerAIResponseError = useCallback(() => {
    setChatLoading(false);
    eventSource.current?.close(); // 停止事件流
    let aiContent = "网络波动,请稍后再试";

    setMessages((prev) => {
      const newMessages = [...prev];
      const lastMessage = newMessages[newMessages.length - 1];
      if (lastMessage && lastMessage.role === "assistant") {
        lastMessage.content += aiContent;
      } else {
        let newAiMessageTemplate = {
          ..._.cloneDeep(aiMessageTemplate),
          id: _.uniqueId("ai_uniqueId_"),
          role: "assistant",
          content: aiContent,
        };
        newMessages.push(newAiMessageTemplate);
      }
      return newMessages;
    });
  }, []);

  // 提问
  const onSendQuestion = useCallback(async () => {
    textareaRef.current!.value = "";
    const question = useQuestionRef.current;
    if (!question?.trim()) return;
    let copyMessageTemplate = {
      ..._.cloneDeep(aiMessageTemplate),
      id: _.uniqueId("user_uniqueId_"),
      role: "user",
      content: question,
      experimental_attachments: uploadFileList?.current?.length
        ? uploadFileList.current.map((v) => {
          return {
            contentType: "image",
            url: v?.result?.fullUrl,
          };
        })
        : [],
    };

    console.log(copyMessageTemplate, "copyMessageTemplatecopyMessageTemplate");
    setMessages((prev) => [...prev, copyMessageTemplate]);
    setChatLoading(true);

    // 清空附件
    uploadFileList.current = [];
    setUserUploadFileList([]);

    try {
      let fileIds = uploadFileList.current.map((v) => v?.result?.fileId);
      let fileIdsStr = fileIds?.join(",") || "";
      eventSource.current = new EventSource(
        `/api/chat/generate?message=${encodeURIComponent(question)}&requestId=${requestId.current
        }&fileIds=${fileIdsStr}`
      );
      eventSource.current.onmessage = (event) => {
        handleAIResponse(event.data);
      };
      eventSource.current.onerror = (event) => {
        // 错误处理
        handlerAIResponseError();
        console.error("Error fetching AI response:", event);
      };
    } catch (error) {
      console.error("Error fetching AI response:", error);
    }
  }, []);

  // 处理提问内容
  const handlerUseQuestion = (value: string) => {
    useQuestionRef.current = value;
    console.log(value, '1111')
    if (value === '/') {
      setPromptState(true)
    }
  };

  // 点击生成文件
  const generateFileClick = (data: any) => {
    console.log(data);
    setCurrentArtifact(data);
    setPreviewStatus(true);

    if (chatLoading) {
      setGenerateEndStatus(false);
    } else {
      setGenerateEndStatus(true);
    }
  };

  //   查询问答记录
  const getChatHistoryFn = async () => {
    try {
      let res = await ChatApi.getChatRecord(requestId.current);
      if (res.code === 200) {
        let resData = res.result || [];
        if (resData.length > 0) {
          setMessages(resData);
        } else {
          // 如果location中带有提问内容 直接进行提问
          if (location?.state?.userQuestion) {
            onSendQuestion();
          } else {
            let newUserMessage = {
              ..._.cloneDeep(userMessageTemplate),
              time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
            };
            setMessages([newUserMessage]);
          }
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 获取用户余额
  const getUserBalanceFn = async () => {
    try {
      let res = await userApi.getUserBalance();
      if (res.code === 200) {
        let resData = res.result;
        dispatch(setCountBalance(resData.countBalance));
      } else {
        console.log(res);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 监听文件上传
  const handlerUpload = (res: any) => {
    if (res[0]?.status == "done") {
      let upload = res[0];
      if (upload?.response?.code === 200) {
        let fileObj = {
          name: upload.name,
          result: upload.response.result,
        };
        setUplodaLoading(false);
        setUserUploadFileList((objFileList: any) => {
          uploadFileList.current = [...objFileList, fileObj];
          return [...objFileList, fileObj];
        });
      }
    }
  };

  // 删除标签
  const handlerTagClose = (data: any) => {
    setUserUploadFileList((objFileList: any) => {
      let newFileList = objFileList.filter((item: any) => {
        return item?.result?.fileId !== data?.result?.fileId;
      });
      uploadFileList.current = newFileList;
      return newFileList;
    });
  };

  useEffect(() => {
    getChatHistoryFn();
  }, []);
  return (
    <div className={styles.chatWarp}>
      <div
        className="chat_content"
        style={{ width: previewStatus ? "50%" : "100%" }}
      >
        <div className="chat_list max-w-3xl">
          <ChatMessageList
            messages={messages as []}
            setCurrentArtifact={setCurrentArtifact}
            generateFileClick={generateFileClick}
            containerRef={messagesRef}
          />
        </div>
        <div className="textarea_box max-w-3xl relative">
          {/* 消息模板 */}

          <div className={` transition-all absolute bottom-[100%] mb-[10px] w-full left-0  ${promptState ? 'h-[auto]' : "h-[0]"} overflow-hidden`}><PromptTemplate setPromptState={setPromptState} /></div>

          <textarea
            ref={textareaRef}
            placeholder="请输入您要提问的内容"
            name=""
            id="chat_textarea"
            onChange={(e) => {
              handlerUseQuestion(e.target.value);
            }}
          ></textarea>

          <div className="question_tools">
            <Upload
              accept=".png,.jpg,.jpeg"
              multiple={true}
              className="mr-[20px]"
              fileList={[]}
              autoUpload
              action="/api/upload/file"
              onChange={handlerUpload}
              beforeUpload={() => {
                return new Promise((resolve, reject) => {
                  setUplodaLoading(true);
                  resolve(true);
                });
              }}
            >
              <Button loading={uplodaLoading} icon={<IconToTop />}></Button>
            </Upload>

            <Button
              loading={chatLoading}
              type="primary"
              icon={<IconSend />}
              className="flex items-center justify-center"
              onClick={() => {
                onSendQuestion();
              }}
            ></Button>
          </div>

          <div className="mt-[5px]">
            {userUploadFileList.map((uploadFile: any) => (
              <Tag
                key={uploadFile?.result?.fileId}
                onClose={() => handlerTagClose(uploadFile)}
                style={{ margin: "0 3px", color: "#000" }}
                closable
              >
                {uploadFile?.name}
              </Tag>
            ))}
          </div>
        </div>
      </div>
      <div
        className="chat_preview"
        style={{ width: previewStatus ? "50%" : "0%" }}
      >
        <ChatPreview
          setPreviewStatus={setPreviewStatus}
          currentArtifact={currentArtifact}
          generateEndStatus={generateEndStatus}
        ></ChatPreview>
      </div>
    </div>
  );
};

export default Chat;
